import {
  _decorator,
  Component,
  Node,
  Sprite,
  UITransform,
  Animation,
  AnimationClip,
  animation,
  Vec3,
  SpriteFrame,
  debug,
} from 'cc'
import { TILE_HEIGHT, TILE_WIDTH } from '../Scripts/Tile/TileManage'
import ResourceManage from '../Runtime/resourceManage'
import {
  CONTROLLER_ENUM,
  DIRECTION_ENUM,
  DIRECTION_ORDER_ENUM,
  ENTITY_STATE_ENUM,
  ENTITY_TYPE_ENUM,
  EVENT_ENUM,
  PARAMS_NAME_ENUM,
} from '../Enums'
import EventManage from '../Runtime/eventManage'
import { EntityManage } from '../Base/EntityManage'
import DataManage from '../Runtime/dataManage'
const { ccclass, property } = _decorator

@ccclass('EnemyManage')
export class EnemyManage extends EntityManage {
  async init(params) {
    // 初始化人物动画状态机
    super.init(params)
    // 监听玩家移动，改变敌人朝向
    EventManage.Instance.on(EVENT_ENUM.PLAYER_BORN, this.onChangeDirection, this)
    EventManage.Instance.on(EVENT_ENUM.PLAYER_MOVE_END, this.onChangeDirection, this)
    EventManage.Instance.on(EVENT_ENUM.ATTACK_ENEMY, this.onDeath, this)

    // 由于玩家可能比敌人先生成，所以敌人生成时也执行该方法，确定敌人的初始朝向
    this.onChangeDirection()
  }
  onDestroy() {
    super.onDestroy()
    EventManage.Instance.off(EVENT_ENUM.PLAYER_BORN, this.onChangeDirection)
    EventManage.Instance.off(EVENT_ENUM.PLAYER_MOVE_END, this.onChangeDirection)
    EventManage.Instance.off(EVENT_ENUM.ATTACK_ENEMY, this.onDeath)
  }
  onChangeDirection() {
    if (this.state === ENTITY_STATE_ENUM.DEATH || !DataManage.Instance.player) return
    let { x: playerX, y: playerY } = DataManage.Instance.player
    const disX = Math.abs(this.x - playerX)
    const disY = Math.abs(this.y - playerY)
    // 判断玩家在以敌人为中心的第几个象限里
    if (playerX >= this.x && playerY <= this.y) {
      // 第一象限
      this.direction = disX > disY ? DIRECTION_ENUM.RIGHT : DIRECTION_ENUM.TOP
    } else if (playerX <= this.x && playerY <= this.y) {
      // 第二象限
      this.direction = disX > disY ? DIRECTION_ENUM.LEFT : DIRECTION_ENUM.TOP
    } else if (playerX <= this.x && playerY >= this.y) {
      // 第三象限
      this.direction = disX > disY ? DIRECTION_ENUM.LEFT : DIRECTION_ENUM.BOTTOM
    } else if (playerX >= this.x && playerY >= this.y) {
      // 第四象限
      this.direction = disX > disY ? DIRECTION_ENUM.RIGHT : DIRECTION_ENUM.BOTTOM
    }
  }
  onDeath(enemyId: string) {
    if (this.id === enemyId) {
      this.state = ENTITY_STATE_ENUM.DEATH
    }
  }
}
